<template>
  <div class="rightPanel-container">
    <div class="rightPanel-background" />
    <div class="rightPanel">
      <div
        class="handle-button"
        :style="{'top': buttonTop+'px','background-color': theme}"
        @click="show=!show"
      >
        <i :class="show?'el-icon-close':'el-icon-setting'" />
      </div>
      <div class="rightPanel-items">
        <slot />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { useStore } from 'vuex'

const store = useStore()
const show = ref(false)
const theme = computed(() => store.state.settings.theme)
const buttonTop = ref(250)

const closeSidebar = (evt: MouseEvent): void => {
  const target = evt.target as HTMLElement
  const parent = target.closest('.rightPanel')
  if (!parent) {
    show.value = false
    document.body.style.overflow = 'auto'
  }
}

watch(show, (val) => {
  if (val) {
    document.body.style.overflow = 'hidden'
    document.addEventListener('click', closeSidebar)
  } else {
    document.body.style.overflow = 'auto'
    document.removeEventListener('click', closeSidebar)
  }
})

onMounted(() => {
  window.addEventListener('resize', () => {
    if (window.innerWidth <= 1200) {
      show.value = false
    }
  })
})

onBeforeUnmount(() => {
  document.body.style.overflow = 'auto'
  document.removeEventListener('click', closeSidebar)
})
</script>

<style>
.rightPanel-background {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 0;
  margin: 0;
  background-color: rgba(0, 0, 0, .5);
  z-index: 0;
}

.rightPanel {
  width: 100%;
  max-width: 260px;
  height: 100vh;
  position: fixed;
  top: 0;
  right: 0;
  box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, .05);
  transition: all .25s cubic-bezier(.7, .3, .1, 1);
  transform: translate(100%, 0);
  background: #fff;
  z-index: 40000;
}

.rightPanel-items {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
}

.rightPanel-container {
  position: relative;
}

.handle-button {
  width: 48px;
  height: 48px;
  position: absolute;
  right: 300px;
  text-align: center;
  font-size: 24px;
  border-radius: 50%;
  z-index: 0;
  pointer-events: auto;
  cursor: pointer;
  color: #fff;
  line-height: 48px;
}

.handle-button i {
  font-size: 24px;
  line-height: 48px;
}
</style>
